#!/usr/bin/php
<?php
	// Prefix for emails we care about
	$subjectPrefix = '[DMDirc] [dmdirc commit]';
	// Command to exec to pass checkin info to
	$execCommand = '/usr/bin/php /home/dmdirc/www/bugs/core/checkin.php';
	// Location of oblong script (or "" to disable)
	$oblongScript = '/home/dmdirc/post-commit/oblong.php';
	// Location to store mail for debugging (or "" to disable)
	$saveLocation = '/home/dmdirc/post-commit/last.mail';

	//----------------------------------------------------------------------

	// Get the mail
	$in = file_get_contents('php://stdin');
	$mail = explode("\n", $in);
	// And Store the mail for debugging
	file_put_contents($saveLocation, $in);
	// Used to decide if we are in the mail header or not
	$info['header'] = true;

	// Who commited this?
	$info['author'] = "";
	// What RV are we on now?
	$info['revision'] = 0;
	// When was the commit?
	$info['date'] = time();

	// Are we getting the log message?
	$info['isLog'] = false;
	// Log Message data
	$info['logData'] = array();

	// File Changes - Modified
	$info['fileChanges']['Modified'] = array();
	// File Changes - Added
	$info['fileChanges']['Added'] = array();
	// File Changes - Deleted
	$info['fileChanges']['Removed'] = array();

	function processLine($line) {
		global $info, $subjectPrefix;

		if ($info['header']) {
			if ($line == "") {
				$info['header'] = false;
			} else {
				$bits = explode(':', $line, 2);
				if ($bits[0] == "Subject") {
					if (!strpos(trim($bits[1]), $subjectPrefix) === 0) {
						return;
					}
				}
			}
		} else {
			if ($info['isLog']) {
				if ($line == "==============================================================================" || $line == "=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=" ) {
					$info['isLog'] = false;
					$last = array_pop($info['logData']);
					$info['log'] = trim(implode("\n", $info['logData']));
					$info['logSingle'] = trim(implode("  ", $info['logData']));
					processLine($last);
				} else {
					$info['logData'][] = $line;
				}
			} else if ($line != "") {
				$bits = explode(':', $line, 2);
				if ($bits[0] == "Author") {
					$info['author'] = trim($bits[1]);
				} else if ($bits[0] == "Date") {
					$info['date'] = strtotime(trim($bits[1]));
				} else if ($bits[0] == "New Revision") {
					$info['revision'] = trim($bits[1]);
				} else if ($bits[0] == "Log") {
					$info['isLog'] = true;
				} else if (isset($info['fileChanges'][$bits[0]])) {
					if (trim($bits[1]) != "") {
						$info['fileChanges'][$bits[0]][] = trim($bits[1]);
					}
				}
			}
		}
	}
	foreach ($mail as $line) { processLine($line); }
	if ($info['isLog']) {
		$info['isLog'] = false;
		$info['log'] = trim(implode("\n", $info['logData']));
		$info['logSingle'] = trim(implode("  ", $info['logData']));
	}

	// Check if the author and revision are known and valid
	if ($info['author'] == '' || $info['revision'] == 0 || !is_numeric($info['revision'])) { return; }
	
	// Check if we already processed this (someimes google code sends more than one email...)
	function e($string) { return mysql_real_escape_string($string); }
	define('DMDIRC', true);
	@include('/home/dmdirc/www/blog/wp-config.php');
	mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	mysql_select_db(DB_NAME);
	mysql_query('LOCK TABLES CommitLog WRITE, CommitLog AS CL READ;');
	$res = mysql_query('select revision from CommitLog as CL WHERE revision=\''.$info['revision'].'\'');
	if (mysql_num_rows($res) != 0) {
		// Existing commit found, don't process twice
		mysql_query('UNLOCK TABLES');
		exit;
	} else {
		$sql = 'insert into CommitLog (revision, author, time, message) VALUES (\''.$info['revision'].'\', \''.e($info['author']).'\', \''.$info['date'].'\', \''.e($info['log']).'\')';
		$res = mysql_query($sql);
		mysql_query('UNLOCK TABLES');
	}

	// Poke oblong if available
	if ($oblongScript != "" && file_exists($oblongScript)) {
		include($oblongScript);
		$message = "Commit by " . $info['author'] . ":";
		$message .= " [RV: ".$info['revision']." http://fisheye.dmdirc.com/changelog/DMDIrc/?cs=".$info['revision']."]";
		$message .= " ";
		$len = 400 - strlen($message);
		$log = $info['logSingle'];
		if (strlen($log) > $len) {
			$message .= substr($info['logSingle'], 0, $len-3);
			$message .= "...";
		} else {
			$message .= $info['logSingle'];
		}
		Oblong($message);
	}

	// This runs an application and returns the process and the pipes in the given array
	// Returns true/false on successful execution
	//
	// $process['pipes'][0] is stdin
	// $process['pipes'][1] is stdout
	function appexec($path, &$process) {
		$descriptorspec = array(0 => array("pipe", "r"),1 => array("pipe", "w"),2 => array("file", "/dev/null", "a"));
		$process = array();
		$process['process'] = proc_open($path, $descriptorspec, $process['pipes']);
		return is_resource($process['process']);
	}

	appexec($execCommand, $proc);
	// Send mantis the details
	fwrite($proc['pipes'][0], "Changes committed in revision ".$info['revision']." by ".$info['author'].":\n");
	fwrite($proc['pipes'][0], $info['log']);
/*	fwrite($proc['pipes'][0], "\n");
	fwrite($proc['pipes'][0], "Files Changed: \n");
	foreach ($info['fileChanges'] as $type => $data) {
		foreach ($data as $file) {
			fwrite($proc['pipes'][0], "\t".$type.": ".$file."\n");
		}
	}*/
	fwrite($proc['pipes'][0], "\n");
	fwrite($proc['pipes'][0], "Fisheye: http://fisheye.dmdirc.com/changelog/DMDIrc/?cs=".$info['revision']."\n");
	fclose($proc['pipes'][0]);

	// Now close the process handle
	//echo stream_get_contents($proc['pipes'][1]);
	fclose($proc['pipes'][1]);
	proc_close($proc['process']);
?>

